import { request } from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart:[],
    totalNum:0,
    totalPrice:0,
    hideModel:false,
    pickway1:true,
    pickway2:false,
    order:{
      id:null,
      pickway:'配送',
      address:null,
      contact:null
    },
    address:"",
    telNumber:"",
    userName:"",
    phone:"",
    consignee:""
  },

  onShow() {
    //从缓存中获取购物车数据
    let cart = wx.getStorageSync('cart') || [];
    cart = cart.filter(v=>v.isCheck);
    this.changeCart(cart);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  changeCart(cart){
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v=>{
      totalPrice += v.price*v.amount
      totalNum += v.amount
    })
    this.setData({
      totalPrice,
      totalNum,
      cart
    })
  },
  //获取购物车列表
  getCart(){
    console.log("getCart")
    const cart = this.data.cart;
    this.changeCart(cart);
  },
  //请求后台创建订单，返回订单信息
  //否则请求后台创建订单并添加时间限制，返回购物车列表，删除购物车已支付数据（后台删除以及缓存删除）
  //由于是个体账户无法对接微信支付api，直接调用后台接口修改订单状态并跳转到订单页面
  handleToPay(){
    const res = this.handlePay(true);
  },
  async handlePay(isPay){
    console.log("是否支付："+isPay);
    //创建订单
    //处理订单主体
    let status = "";
    let pickupWay = "";
    let address = "";
    let contact = "";
    let consignee = ""
    if(isPay){
      status = "PAID";
    }else{
      status="CANCEL";
    }
    if(this.data.pickway1){//配送
      address = this.data.address;
      pickupWay = "deliver";
      contact = this.data.telNumber;
      consignee = this.data.userName;
    }else{//自提
      address = null;
      pickupWay = "invite";
      contact = this.data.phone;
      consignee = this.data.consignee;
    }
    const userInfo = wx.getStorageSync('userinfo')
    const order = {
      userId:userInfo.id,
      address:address,
      pickupWay:pickupWay,
      contact:contact,
      originalPrice:this.data.totalPrice.toFixed(2),
      totalNum:this.data.totalNum,
      contact:contact,
      consignee:consignee,
      status:status,
      payWay:"线上支付"
    };
    //处理订单明细
    let orderDetail = [];
    const cart = this.data.cart;
    cart.forEach(v=>{
      orderDetail.push({
        goodsId:v.goodsId,
        amount:v.amount
      });
    })
    //请求后台
    let param = {
      orderJson:JSON.stringify(order),
      detailsJson:JSON.stringify(orderDetail)
    }
    const res = await request({ url: "order/save", data: param, method: 'POST' });
    if(res.success){
      let orderId = res.data;
      //清除缓存
      let newCart = wx.getStorageSync('cart') || [];
      newCart = newCart.filter(v=>v.isCheck);
      wx.setStorageSync('cart', newCart);
      //前往订单明细页面
      if(res.data){
        wx.redirectTo({
          url: '/pages/orderDetail/index?orderId='+orderId
        })
      }
    }else{
      wx.showToast({
        title: res.msg,
        icon: 'none',
        mask: true
      });
      //关闭抽屉
      this.setData({
        hideModel: false
      })
      return;
    }
  },
  powerDrawer(e){
    var {statu} = e.currentTarget.dataset
    this.util(statu); 
  },
  util(statu){
    //创建动画实例
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0,
    });
    //赋值给动画实例
    this.animation = animation;
    animation.translateY(240).step();
    this.setData({
      animationData:animation.export()
    })
    setTimeout(function(){
      animation.translateY(0).step();
      this.setData({
        animationData:animation
      })
      //关闭抽屉
      if(statu === "close"){
        this.setData({
          hideModel: false
        })
        this.handlePay(false);
      };
    }.bind(this),200);
    if(statu==="open"){
      let bool = this.checkOrderInfo();
      if(!bool){
        return;
      }
      this.setData({
        hideModel: true
      });
    }
  },
  checkOrderInfo(){
    if(this.data.pickway1){//配送
      let address = this.data.address;
      if(!address){
        wx.showToast({
          title: '请选择配送地址！',
          icon: 'none',
          mask: true
        });
        return false;
      }
      return true;
    }else{//自提
      let contact = this.data.phone;
      let consignee = this.data.consignee;
      if(!consignee){
        wx.showToast({
          title: '请输入收货人姓名！',
          icon: 'none',
          mask: true
        });
        return false;
      }else if(!contact){
        wx.showToast({
          title: '请输入预留电话！',
          icon: 'none',
          mask: true
        });
        return false;
      }
      return true;
    }
  },
  radioChange(e) {
    const value = e.detail.value;
    if(value==='p1'){
      this.setData({
        pickway1:true,
        pickway2:false
      })
    }else{
      this.setData({
        pickway1:false,
        pickway2:true
      })
    }
    //修改显示
  },
  wxAddress(){
    let that = this;
    wx.chooseAddress({
      success: function (res) {
        //cityName: "广州市"
        // countyName: "海珠区"
        // detailInfo: "新港中路397号"
        // errMsg: "chooseAddress:ok"
        // nationalCode: "510000"
        // postalCode: "510000"
        // provinceName: "广东省"
        // telNumber: "020-81167888"
        // userName: "张三"
        let address = res.provinceName+res.cityName+res.countyName+res.detailInfo;
        that.setData({
          address,
          telNumber:res.telNumber,
          userName:res.userName
        })
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  getTelNumber(e){
    this.setData({
      phone:e.detail.value
    })
  },
  getConsignee(e){
    this.setData({
      consignee:e.detail.value
    })
  }
})